/**
 * @NApiVersion 2.x
 * @NScriptType MapReduceScript
 */
define(['N/search', 'N/record', "N/http",], function (search, record, http) {

    function getInputData() {
        return search.create({
            type: 'customrecord_fba_inbound_shipment',
            columns: ['custrecord_inbound_shipmentid',
                'custrecord_inbound_store.custrecord_store_seller_id',
                'custrecord_inbound_store',
                'custrecord_inbound_fromlocation',
                'custrecord_inbound_tolocation',
                'custrecord_inbound_boxquantity',
                'custrecord_inbound_vendor'],
            filters: [['custrecord_inbound_po', 'isnotempty', '']
                , 'and', ['custrecord_inbound_so', 'isnotempty', '']]
        }).run().getRange(0, 30);
    }

    function map(context) {
        var recId = JSON.parse(context.value).id;
        var result = JSON.parse(context.value).values;
        log.debug('result', result);
        var sellerId = result['custrecord_inbound_store.custrecord_store_seller_id'];
        var storeId = result['custrecord_inbound_store'][0].value;
        var shipmentId = result['custrecord_inbound_shipmentid'];
        var fromLocationId = result['custrecord_inbound_fromlocation'][0].value;
        var toLocationId = result['custrecord_inbound_tolocation'][0].value;
        var boxQuantity = result['custrecord_inbound_boxquantity'];
        var poId = '';
        log.debug('shipmentId', shipmentId);
        log.debug('sellerId', sellerId);
        log.debug('fromLocationId', fromLocationId);
        log.debug('toLocationId', toLocationId);
        log.debug('storeId', storeId);
        var listShipmentRequestBody = {
            "sellerId": sellerId,
            "shipmentIds": [shipmentId]
        };
        try {//try name : post o2o
            var response = http.post({//获得亚马逊入库状态,并更新  亚马逊入库单状态
                url: "http://112.74.55.237:8001/inbound/listInboundShipment",
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "*/*"
                },
                body: JSON.stringify(listShipmentRequestBody)
            });
            log.debug({title: 'listShipmentRequestBody', details: JSON.stringify(listShipmentRequestBody)});
            log.debug({title: 'listShipmentRequestBodyresponse', details: JSON.stringify(response)});
            if (response.code == 200) {
                var responseBody = JSON.parse(response.body);
                var members = responseBody.ListInboundShipmentsResult.ShipmentData.Member;
                var shipmentStatus = members[0].ShipmentStatus;
                log.debug({title: 'shipmentStatus', details: JSON.stringify(shipmentStatus)});
                if (shipmentStatus.toUpperCase() == "CLOSED" || shipmentStatus.toUpperCase() == "RECEIVING") {

                }
                record.submitFields({
                    type: 'customrecord_fba_inbound_shipment',
                    id: recId,
                    values: {
                        'custrecord_inbound_shipmentstatus': shipmentStatus.toUpperCase()
                    }
                });
            } else {
                throw response.body;
            }
        } catch (e) {
            log.error({title: "error", details: JSON.stringify(e)});
            throw JSON.stringify(e);
        }

        //
        // var requestBody = {
        //     "sellerId": sellerId,
        //     "shipmentId": shipmentId,
        //     "nextToken": ""
        // };
        // var members;
        // try {//try name : update ids
        //     do {
        //         try {  //try name : post o2o  抛异常给 update ids
        //             var response = http.post({
        //                 url: "http://112.74.55.237:8001/inbound/listInboundShipmentItems",
        //                 headers: {
        //                     "Content-Type": "application/json",
        //                     "Accept": "*/*"
        //                 },
        //                 body: JSON.stringify(requestBody)
        //             });
        //             log.debug({title: 'requestBody', details: JSON.stringify(requestBody)});
        //             log.debug({title: 'response', details: JSON.stringify(response)});
        //             if (response.code == 200) {
        //                 var responseBody = JSON.parse(response.body);
        //                 if (requestBody.nextToken != "") {
        //                     members = responseBody.ListInboundShipmentItemsByNextTokenResult.ItemData.Member;
        //                 } else {
        //                     members = responseBody.ListInboundShipmentItemsResult.ItemData.Member;
        //                 }
        //                 var nextToken;
        //                 if (requestBody.nextToken != "") {
        //                     nextToken = responseBody.ListInboundShipmentItemsByNextTokenResult.NextToken;
        //                 } else {
        //                     nextToken = responseBody.ListInboundShipmentItemsResult.NextToken;
        //                 }
        //                 if (nextToken) {
        //                     requestBody.nextToken = nextToken;
        //                 } else {
        //                     requestBody.nextToken = "";
        //                     break;
        //                 }
        //             } else {
        //                 requestBody.nextToken = "";
        //                 throw response.body;
        //             }
        //         } catch (e) {
        //             requestBody.nextToken = "";
        //             log.debug({title: "error", details: JSON.stringify(e)});
        //             throw JSON.stringify(e);
        //         }
        //     } while (requestBody.nextToken != "");
        //     var amzReceiveItemData = {};
        //     for (var j = 0; j < members.length; j++) {
        //         var itemId;
        //         try {
        //             itemId = getItemIdBySellerSkuAndStoreId(members[j].SellerSKU, storeId);
        //         } catch (e) {
        //         }
        //         if (amzReceiveItemData[itemId]) {
        //             amzReceiveItemData[itemId] += members[j].QuantityReceived;
        //         } else {
        //             amzReceiveItemData[itemId] = members[j].QuantityReceived;
        //         }
        //     }
        //     log.audit("亚马逊收到的商品", JSON.stringify(amzReceiveItemData));
        //     var soIfItemData = getSoItemFulfillmentItemData(poId);
        //     log.audit("销售单发货的商品", JSON.stringify(soIfItemData));
        //     var itemReceiptId;
        //     try { //try name : create ir  抛异常给update ids
        //         var itemReceipt = getPoItemReceiptRec(poId);
        //         var itemLineCount = itemReceipt.getLineCount('item');
        //         for (var i = 0; i < itemLineCount; i++) {
        //             var itemId = itemReceipt.getSublistValue('item', 'item', i);
        //             var itemName = itemReceipt.getSublistText('item', 'item', i);
        //             var quantity = itemReceipt.getSublistValue('item', 'quantity', i);
        //             var receiptQuantity = amzReceiveItemData[itemId];
        //             var fulfillmentQuantity = soIfItemData[itemId];
        //             log.debug("第" + i + "行", "itemName:" + itemName + "itemId:" + itemId
        //                 + ",采购收货单上的数量" + quantity
        //                 + ",销售发货单上的数量" + fulfillmentQuantity
        //                 + ",亚马逊收到的数量" + receiptQuantity
        //             );
        //             //采购收货单的数量 不等于 销售发货单上的数量
        //             if (quantity != fulfillmentQuantity) {
        //                 itemReceipt.setSublistValue('item', 'quantity', i, receiptQuantity);  //设置采购收货单数量
        //             } else {
        //                 errorMsg += "收货单上没找到发货单上的此商品:" + itemId + "\r\n";
        //             }
        //         }
        //         itemReceiptId = itemReceipt.save();
        //     } catch (e) {
        //         log.error({title: "发货单创建失败", details: JSON.stringify(e)});
        //         throw JSON.stringify(e);
        //     }
        //     log.audit({title: "发货单创建成功", details: itemReceiptId});
        // } catch (e) {
        //     log.error({title: "更新shipmentIds失败", details: JSON.stringify(e)});
        //     // record.submitFields({
        //     //     type: 'customrecord_fba_inbound_shipment_ids',
        //     //     id: recId,
        //     //     values: {
        //     //         'custrecord_fba_shipment_msg': JSON.stringify(e),
        //     //         'custrecord_fba_shipment_id_status': 17
        //     //     }
        //     // });
        // }

    }

    function getPoItemReceiptRec(poId) {//po单收货
        var poItemReceiptId;
        var poItemReceiptRec;
        search.create({
            type: 'itemreceipt',
            columns: [],
            filters: ['createdfrom', 'is', poId]
        }).run().each(function (result) {
            poItemReceiptId = result.id;
        });
        if (poItemReceiptId) {
            poItemReceiptRec = record.load({
                type: 'itemreceipt',
                id: poItemReceiptId,
                idDynamic: true
            });
        } else {
            poItemReceiptRec = record.transform({
                fromType: 'purchaseorder',
                fromId: poId,
                toType: 'itemreceipt'
            });
        }
        return poItemReceiptRec;
    }

    function getSoItemFulfillmentItemData(soId) {//so单发货
        var itemFulfillmentId;
        var soIfItemData = {};
        search.create({
            type: 'itemfulfillment',
            columns: [],
            filters: ['createdfrom', 'is', soId]
        }).run().each(function (result) {
            itemFulfillmentId = result.id;
        });
        if (itemFulfillmentId) {
            log.debug({title: '找到对应的发货单', details: itemFulfillmentId});
            var soIf = record.load({
                type: 'itemfulfillment',
                id: itemFulfillmentId,
                idDynamic: true
            });
            var itemLineCount = soIf.getLineCount('item');
            log.debug({title: 'itemLineCount', details: itemLineCount});
            for (var i = 0; i < itemLineCount; i++) {
                var itemId = soIf.getSublistValue('item', 'item', i);
                var quantity = soIf.getSublistValue('item', 'quantity', i);
                soIfItemData[itemId] = quantity;
            }
        } else {
            log.debug('未找到对应的发货单', "未找到对应的发货单");
        }
        return soIfItemData;
    }

    function reduce(context) {
    }

    function summarize(summary) {
    }


    function getItemIdBySellerSkuAndStoreId(sellerSku, storeId) {
        var itemId;
        search.create({
            type: 'kititem',
            columns: [],
            filters: [['custitem_platformsku', 'is', sellerSku],
                'and', ['custitem_platform_store_information', 'is', storeId]]
        }).run().each(function (result) {
            itemId = result.id;
        });
        return itemId;
    }

    return {
        getInputData: getInputData,
        map: map,
        reduce: reduce,
        summarize: summarize
    };
});